package com.chenwy.example.configuration;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLiteDB {

    private ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    public SQLiteDB(){
        try {
            Class<Driver> driverClass = (Class<Driver>) Class.forName("org.sqlite.JDBC");
            Driver driver = driverClass.newInstance();
            DriverManager.registerDriver(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public  Connection getConnection() throws SQLException {
        Connection connection = connectionThreadLocal.get();
        if(connection == null){
            connection = DriverManager.getConnection("jdbc:sqlite::resource:sqlite/sqlite.db");
            connectionThreadLocal.set(connection);
        }
        return connection;
    }

    public void destroy(){

    }

    public static void main(String [] args){
        SQLiteDB sqLiteDB = new SQLiteDB();
        try {
            Connection connection = sqLiteDB.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
